package com.wowotou.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    private void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 交换机确认回调方法
     * @param correlationData   保存回调消息的ID和内容
     * @param ack ack
     * @param s 原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String s) {
        if(correlationData != null){
            String id = correlationData.getId() == null ? "" : correlationData.getId();
            if(ack){
                log.info("交换机收到消息：{}",correlationData);
            }else {
                log.info("交换机未收到消息，原因为：{}",s);
            }
        }
        }

    /**
     * 将交换机未成功发送的消息回退
     * @param returnedMessage   回退的消息内容
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("发送失败！消息为：{}，交换机为：{}，路由为：{}，原因为：{}"
                ,new String(returnedMessage.getMessage().getBody())
                ,returnedMessage.getExchange()
                ,returnedMessage.getRoutingKey()
                ,returnedMessage.getReplyText()
        );
    }
}
